<?php
namespace control;
// 设备保养
class equipmentMaintenanceClass extends adIndexClass
{
	private const page        = 'equipmentMaintenance';
	private const table       = 'equipment_patrol';
	private const tableTarget = 'equipment';
	private const title       = '设备保养';
	private const type        = '设备保养';
	private const state       = ['正常', '异常'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'code'  => [
                        'name'  => '设备编号',
                        'width' => 200,
                    ],
                    'name'         => [
                        'name'  => '设备名称',
                        'width' => 200,
                    ],
                    'lastDate'          => [
                        'name'  => '上次保养日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'items'          => [
                        'name'  => '保养内容',
                        'width' => 150,
                    ],
                    'state'          => [
                        'name'  => '保养结果',
                        'width' => 150,
                    ],
                    'text'          => [
                        'name'  => '不通过内容',
                        'width' => 150,
                    ],
                    'stid'          => [
                        'name'  => '保养人',
                        'width' => 100,
                    ],
                    'updateTime'          => [
                        'name'  => '保养时间',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号"   => text(array("name" => "orderNo")),
                    "设备编号"   => text(array("name" => "eqCode")),
                    "设备名称"   => text(array("name" => "eqName")),
                ],
                [
                    "点检结果"   => select(["name" => "state", "title" => "点检结果", 'option' => self::state]),
                    "点检人"   => selectMultiple(['table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'stid']),
                    "保养时间" => text(['name' => 'lastDate', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 列表-查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 客户列表-查询结果
	 *
	 * @return bool|string
	 */
	public function homeSearch(): string
	{
		//查询结果
		$equal = [
			'state' => $this->post('state'),
			'stid'  => $this->post('stid'),
			'coid'  => self::$coid,
			'type'  => self::type,
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
		];
		//生成查询语句
		$where = search([
			"="    => $equal,
			"like" => $like,
		]);
		//生成子查询语句
		$targetWhere = search([
			"like" => [
				'code' => $this->post('eqCode'),
				'name' => $this->post('eqName'),
			],
		]);
		if ($targetWhere) {
			$where .= " and eqid IN (SELECT id FROM `equipment` WHERE 1=1 $targetWhere) ";
		}
		if ($this->post('lastDate')) {
			$where .= self::timeComparison($this->post('lastDate'), 'date', 'lastDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate  = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
				"edit"   => $array['state'] !== '已确认' ? ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"] : [],
			);
			$equipment = query(self::tableTarget, " id = '$array[eqid]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'code':
                    case 'name':
                        $row[] = $equipment[$key];
                        break;
                    case 'items':
                        $detail    = json_decode($array['detail'], true);
                        $items     = implode('；', array_column($detail, 'item'));
                        $row[] = $items;
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id       = $this->get('id');
		$info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
		$button[] = [
			'style' => 'li-btn-blue-bg',
			"name"  => "保存",
			"type"  => "点击事件",
			"title" => "保存",
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
		$tr[]     = ['', '保养项目', '保养要求', '保养结果', '备注'];
		$result   = !empty($info['detail']) ? json_decode($info['detail'], true) : [];
		foreach ($result as $k => $array) {
			$tr[] = [
                componentClass::tablePperation($k + 1) ,
				$array['item'],
                $array['ask'],
				radio(['name' => "result[$k]", 'class' => 'text', 'value' => self::state, 'checked' => $array['result']]),
				text(['name' => 'text[]', 'class' => 'text', 'value' => $array['text'], 'title' => '请填写']),
			];
		}
		$table = $this->listTable(['tr' => $tr, 'end' => true]);
		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '设备' => hidden(['name' => 'eqid', 'value' => $info['eqid']])
                        . '<span id="equipmentName">' . ($info['eqid'] ? query('equipment', "id = '$info[eqid]'", 'name')['name'] : '未选择') . '</span>'
                        . "<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addTarget',{})\" style='margin-left: 10px'>选择</span>",
                    '保养频次' => '<span id="frequency">' . ($info['frequency'] ?: ($info['id']?'-':'请选择')) . '</span>',
                    '上次保养日期' => '<span id="lastDate">' . ($info['lastDate'] ?: ($info['id']?'-':'请选择')) . '</span>',
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => $this->get('cla').'EditTable',
            'title' => '保养项目',
            'html' => $table,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]) . hidden(['name' => 'tpid', 'value' => $info['tpid']]),
		]);
		$data['html'] .= <<<EOT
		<script>
		//选择明细
        function addTarget(){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addTargetEdit', $("form[name='mxForm']").serialize(),function(resp) {
	         if (resp.warn === 2){
	            $("[name='eqid']").val(resp.res.eqid);
                $("[name='tpid']").val(resp.res.tpid);
                $('#equipmentName').html(resp.res.name)
                $('#frequency').html(resp.res.frequency)
                $('#lastDate').html(resp.res.lastDate)
	            $('#{$this->get('cla')}EditTable').find('tbody').html(resp.res.html);
	         }else{
	             msg(resp.warn);
	         }
	        },'json');
        }
        
		</script>
EOT;
		//返回
		return $this->tab($data);
	}

	/**
	 *选择生产设备
	 *
	 * @return bool|string
	 */
	public function addTarget(): bool|string
	{
		$html   =
			select(["name" => "type", "title" => "分类", "option" => explode('，', para('equipmentType'))]) .
			text(["name" => "code", "title" => "设备编号"]) .
			text(["name" => "name", "title" => "设备名称"]) .
			text(["name" => "model", "title" => "规格型号"]);
		$button = "<input style='margin-left: 5px' onclick=\"addTarget();$('#" . self::page . "AddTarget').hide()\" type='button' class='searchSub' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(["title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button]);
	}

	/**
	 *添加设备
	 */
	public function addTargetSearch(): bool|string
	{
		$like  = [
			'name'  => $this->post('name'),
			'code'  => $this->post('code'),
			'model' => $this->post('model'),
		];
		$equal = [
			'type'  => $this->post('type'),
			'state' => '正常',
			'coid'  => self::$coid,
		];
		$where = search(["like" => $like, "=" => $equal]);
		$page  = $this->page([
			"table" => self::tableTarget,
			"where" => $where,
			"order" => "time ASC",
		]);
		//获取表头
		$tr[] = ['', '分类', '设备编号', '设备名称', '厂家', '规格型号', '存放地点'];
		//获取记录
		foreach ($page['array'] as $array) {
			$tr[] = array(
				"<input name='mxId' value='$array[id]' type='radio' class='radio-bigger'>",
				$array['type'],
				$array['code'],
				$array['name'],
				$array['factory'],
				$array['model'],
				'存放地点',
			);
		}
		$json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addTargetEdit(): bool|string
	{
		$eqid = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($eqid)) {
			$json['warn'] = '请选择设备';
		} else {
			$equipment = query(self::tableTarget, "id = '$eqid' ");
			$tpl       = query('equipment_patrol_tpl', "eqid = '$eqid' AND type ='保养计划' ", 'id, type, frequency, detail');
			if (empty($tpl['id'])) {
				$json['warn'] = '该设备暂无保养计划';
			} else {
				$lastData      = query('equipment_patrol', " eqid = '$eqid' AND tpid = '$tpl[id]' ORDER BY time DESC ",'DATE(time) as lastDate');
				$tpl['detail'] = json_decode($tpl['detail'], true);
                $tr = [];
                foreach ($tpl['detail'] as $k => $array) {
                    $tr[] = [
                        componentClass::tablePperation($k + 1) ,
                        $array['item'],
                        $array['ask'],
                        radio(['name' => "result[$k]", 'class' => 'text', 'value' => self::state, 'checked' => '']),
                        text(['name' => 'text[]', 'class' => 'text', 'value' => '', 'title' => '请填写']),
                    ];
                }
				$json = [
					'warn' => 2,
					'res'  => [
						'name'      => $equipment['code'] . '-' . $equipment['name'] . '-' . $equipment['model'],
						'eqid'      => $equipment['id'],
						'tpid'      => $tpl['id'],
						'frequency' => $tpl['frequency'],
						'lastDate'  => $lastData['lastDate'],
						'html'      => $this->tableMany(['tr' => $tr, 'thead' => false]),
					],
				];
			}
		}
		return json_encode($json, 320);
	}


	/**
	 * 编辑报错
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id         = $this->post('id') ?: self::getId();
		$results    = $this->post('result');
		$texts      = $this->post('text');
		$field      = [
			'eqid' => $this->post('eqid'),
			'tpid' => $this->post('tpid'),
			'type' => self::type,
		];
		$annotation = [
			'eqid' => '设备ID',
			'tpid' => '计划ID',
			'type' => '类型',
		];
		$rules      = [
			'eqid' => 'required',
			'tpid' => 'required',
			'type' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		$tpl   = query('equipment_patrol_tpl', " id = '$field[tpid]' ");
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($results)) {
			$json['warn'] = "请选择保养结果";
		} elseif (empty($tpl['id'])) {
			$json['warn'] = "保养计划不存在";
		} else {
			$data           = [];
			$detail         = json_decode($tpl['detail'], true);
			$field['state'] = in_array('异常', $results) ? '异常' : '正常';
			$field['text']  = '';
			// 上次处理日期
            $last = query(self::table, " coid = '" . self::$coid . "' AND eqid = '$field[eqid]' AND type ='" . self::type . "' AND id <> '$id' ORDER by time DESC  ", 'DATE(time) as date');
            $field['lastDate'] = isset($last['date']) ? $last['date'] : null;
			foreach ($results as $k => $result) {
				$field['text'] .= ($result === '异常') ? $detail[$k]['item'] . '<br>' : '';
				$data[]        = [
					'item'   => $detail[$k]['item'],
					'ask'    => $detail[$k]['ask'],
					'result' => $result,
					'text'   => $texts[$k],
				];
			}
			$field['detail'] = json_encode($data, 256);
			$this->startTrans();
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'SBBY' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND type = '" . self::type . "' AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'        => $id,
					'orderNo'   => $orderNo,
					'frequency' => $tpl['frequency'],
					'coid'      => self::$coid,
					'stid'      => $this->control['stid'],
				]);
				$json['warn'] = static::insert([
					"table" => self::table,
					"field" => $field,
				]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			$equipment = query(self::tableTarget, " id = '$info[eqid]' ");
			//菜单
			$data = array(
				"id" => $info['id'],
			);
			//按钮
			$button[] = [
				"name"  => "编辑",
				"type"  => "顶部页卡",
				"title" => "编辑用户",
				"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
				'style' => 'li-btn-blue-bg',
			];
			//按钮
			$button[] = [
				"name" => "删除",
				"type" => "弹出层",
				"cla"  => $this->get('cla'),
				"fun"  => "operate",
				"post" => ["act" => 'del', "id" => $info['id']],
			];
			// 明细列表
			$mxtr[] = ['保养项目', '保养要求', '保养结果', '备注'];
			$result = json_decode($info['detail'], true);
			foreach ($result as $array) {
				$mxtr[] = [
					$array['item'],
					$array['ask'],
					$array['result'],
					$array['text'],
				];
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				[
					[
						"设备" => $equipment['code'] . ' - ' . $equipment['name'] . ' - ' . $equipment['model'],
						"保养频次"   => $info['frequency'],
						"上次保养日期" => $info['lastDate'],
					],
				],
			]);
            $data['html'] .= $this->detailList([
                'title' => '保养项目',
                'html' => $this->listTable(['tr' => $mxtr, 'showSort' => true]),
            ]);
            $data['html'] .= $this->tableShow([
                '系统信息'   => [
                    [
                        "单据编号" => $info['orderNo'],
                        "保养人"  => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                    ],
                ],
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	// 操作中转
	public function operate(): bool|string
	{
		$act = $this->post('act') ?? '';
		// 需要密码
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => false,
				'word'     => false,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '已审核') {
					$warn = "删除失败：已审核，暂不能删除";
				} else {
					//最后删除基本参数
					delete(["table" => self::table, "where" => " id = '$id' "]);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}

	/**
	 * 保养计划
	 *
	 * @return string
	 */
	public function maintenance(): string
	{
		$eqid = $this->get('id');
		$info = query('equipment', " id = '$eqid' ");
		if (!$this->power('equipment', "maintenance")) {
            $json['html'] = "你没有查看权限";
		} elseif (empty($info['id'])) {
            $json['html'] = "设备信息不存在";
		} else {
			// table
			$tpl    = query('equipment_patrol_tpl', " eqid = '{$info['id']}'  AND type = '保养计划' ");
			$tr[]   = ['保养项目', '保养要求', '操作'];
			$result = !empty($tpl['detail']) ? json_decode($tpl['detail'], true) : [];
            if(count($result) > 0) {
                foreach ($result as $k => $array) {
                    $array['list'] = $k + 1;
                    $tr[]          = $this->listRow($array);
                }
            }else{
                $tr[] = $this->listRow(['mxId'=>self::getId(), 'list'=>1]);
            }
            $table = $this->tableMany(['tr' => $tr, 'end' => true, 'displayFields' => false]);
			//生成页面
			$html = $this->tableEdit([
				[
					'保养频次'  => radio([
						'name'    => 'frequency',
						'value'   => ['每天', '每周', '每半月', '每月'],
						'checked' => $tpl['frequency'],
					]),
					'计划保养人' => selectMultiple(['table' => 'staff', "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'stid', 'value' => $tpl['stid'], 'name' => 'stid']),
					'&nbsp' => hidden(['name' => 'eqid', 'value' => $eqid]),
				],
			]);

            // 按钮
            $button = <<<EOT
            <div class="tab-button">
                <span onclick="subForm('maintenanceForm', root+'control/adIndex.html?cla=equipmentMaintenance&fun=maintenanceEdit')" class="spanButton li-btn-blue-bg">保存</span>
            </div>
    EOT;
            //JS
            $js           = <<<EOT
            <script>
              function addRowMaintenance(e){
                 $.post(root+'control/adIndex.php?cla={$this->get('cla')}&fun=addRow',{},function (res){
                   $(e).closest('tr').after(res.data);
                    resetNumber($(e).closest('tbody'))
                 },'json');
             }
            </script>
    EOT;
            $json['html'] =
            "<div class='tab-box'>".
                $button .
                "<div class='tab-content p-l-r-10'>
                    <form name='maintenanceForm'>" .
                    $html .
                    space .
                    $table .
                    "</form>" .
                    $js.
                "</div>
            </div>"
            ;
        }
		//返回
		return json_encode($json, 320);
	}

	/**
	 * 保养保存
	 *
	 * @return string
	 */
	public function maintenanceEdit(): string
	{
		$items      = $this->post('item');
		$asks       = $this->post('ask');
		$field      = [
			'eqid'      => $this->post('eqid'),
			'frequency' => $this->post('frequency'),
			'stid'      => $this->post('stid'),
			'type'      => '保养计划',
		];
		$annotation = [
			'eqid'      => '设备ID',
			'stid'      => '保养人',
			'frequency' => '频次',
			'type'      => '类型',
		];
		$rules      = [
			'eqid'      => 'required',
			'stid'      => 'required',
			'frequency' => 'required',
			'type'      => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$title = '保养计划';
		$where = " eqid = '{$field['eqid']}' AND type='$title' ";
		$table = 'equipment_patrol_tpl';
		$page  = 'equipment';
		$menu  = $power = 'maintenance';
		$info  = query($table, $where);
		//判断
		if (!$this->power($page, $power)) {
			$json['warn'] = "你没有编辑" . $title . "的权限";
		} else {
			$data = [];
			if (is_array($items)){
                foreach ($items as $k => $item) {
                    $mxField = [
                        'item' => $item,
                        'ask'  => $asks[$k],
                    ];
                    if(empty(array_filter($mxField, 'strlen'))) {
                        continue;
                    }
                    $data[] = $mxField;
                }
            }
			$field['detail'] = json_encode($data, 256);
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$field        = array_merge($field, [
					'id'   => self::getId(),
					'coid' => self::$coid,
				]);
				$json['warn'] = static::insert(["table" => $table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => $table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . $title . " 设备id：【" . $field['eqid'] . '】';
				$this->logText(["type" => $page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=equipment&fun=detail&menu=$menu&id=" . $field['eqid'];
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}

    /**
     * Desc : 保养计划
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function listRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['mxId'])&&$data['mxId']?$data['mxId']:self::getId();
        $field = ['item', 'ask'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'listRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRowMaintenance(this)"),
            text(['name' => 'item[]', 'class' => 'text', 'title' => '请填写项目', 'value' => $array['item']]),
            text(['name' => 'ask[]', 'class' => 'text', 'title' => '请填写要求', 'value' => $array['ask']]),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     * 添加一行
     *
     * @return string
     */
    public function addRow(): string
    {
        $res = json_decode($this->listRow(),true);
        $json['data'] = $res['html'];
        return json_encode($json, 320);
    }
}
